var express = require('express');
var router = express.Router();
const db = require('./db');
// const crypto = require('crypto');


// 设置跨域
router.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next()
});

router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 学生信息查询
router.get('/manage', function (req, res, next) {
  db("SELECT * FROM `student`", (error, data) => {
    res.json(data)
    console.log(data)
  })
});

//添加信息
router.post('/add', function (req, res, next) {
  const param = [req.body.IDNumber, req.body.name, req.body.StudentNumber, req.body.school, req.body.add_time, req.body.login_assword, req.body.admission_time, req.body.gender];
  console.log(param);
  let addsql = 'INSERT INTO student (id, IDNumber, name, StudentNumber, school, add_time, login_assword, admission_time, gender) VALUES (0, ?, ?, ?, ?, ?, ?, ?, ?)';
    db(addsql, param, function (err, result) {
    if (err) {
      return console.log(err);
    }else{
    console.log(result);
    console.log('添加成功');
    }
  })
})

// 删除信息
router.post('/del', function (req, res, next) {
  const params = [req.body.id]
  let addsql = 'delete from student where id=?';
  db(addsql, params, function (err, result) {
    if (err) {
      return console.log(err);
    }
    console.log(result);
    console.log('删除成功');
  })
})

// 修改信息
router.post('/modify', function (req, res, next) {
  const params_ = [req.body.IDNumber, req.body.name, req.body.StudentNumber, req.body.school, req.body.add_time, req.body.admission_time, req.body.id]
  let modifysql = 'UPDATE student SET IDNumber =?, name =?, StudentNumber =?, school =?, add_time =?, admission_time =? WHERE student.id =?';
  db(modifysql, params_, function (err, result) {
    if (err) {
      return console.log(err);
    }
    console.log(result);
    console.log('修改成功');
  })
})

// 搜索
router.post('/search', function(req, res, next){
  const params = req.body.name
  console.log(params)
  let sql = `SELECT * FROM student where name like '%${params}%'`
  db(sql, (error, data)=>{
		let rows = JSON.stringify(data);
		res.send(rows)
	})
})

module.exports = router;